<template>
    <el-popover v-model="data.isPopoverVisible" :disabled="disabled" @after-leave="resetSearcher"
                placement="bottom-start" width="auto">
        <el-input placeholder="搜索房号" v-model="searchLoader.baseParams.roomCode" @input="search"></el-input>
        <div class="mt-2 max-h-[500px] relative flex">
            <MultipleSelect v-if="multiple" class="overflow-auto" :value="rooms" @input="onInput" ref="treeSelectRef"/>
            <SingleSelect v-else class="overflow-auto" :value="room" @input="onSingleInput" ref="treeSelectRef"/>
            <div v-if="searchLoader.isLoading || searchLoader.data || searchLoader.error"
                 class="overflow-auto absolute top-0 left-0 right-0 bottom-0 bg-white z-10">
                <div class="px-4 py-2 hover:bg-[#FEF9F0] hover:text-[#DBBC81]" v-for="room in searchLoader.data"
                     :key="room.id" @click="onSelect(room)">
                    {{room.address}}
                </div>
                <el-empty v-if="searchLoader.data && !searchLoader.data.length" description="无搜索结果"></el-empty>
                <el-result v-if="searchLoader.error" icon="error" title="错误提示" :subTitle="searchLoader.error.message">
                </el-result>
            </div>
        </div>
        <el-input slot="reference" :value="displayValue" :disabled="disabled" placeholder="请选择项目/分期/楼栋/单元/房屋" readonly
                  ref="inputRef"></el-input>
    </el-popover>
</template>

<script setup lang="ts">
import { type ElInput } from 'element-ui/types/input';
import { computed, reactive, ref, watch } from 'vue';
import MultipleSelect, { RoomSelector } from './MultipleSelect.vue';
import * as api from './api';
import { Loader } from 'src/framework/network/Loader';
import { debounce } from 'lodash';
import SingleSelect from './SingleSelect.vue';


const props = defineProps<{
    room?: string,
    rooms?: RoomSelector,
    disabled?: boolean,
    multiple?: boolean
}>()

const emit = defineEmits<{
    (event: 'update:rooms', rooms?: RoomSelector): void
    (event: 'update:room', room?: string): void
}>()

const data = reactive({
    isPopoverVisible: false,
    roomLoader: new Loader(api.queryRoom)
})


const displayValue = computed(() => {
    if (props.multiple) {
        if (props.rooms) {
            let rooms = ''
            if (props.rooms.village.length) {
                rooms += props.rooms.village.length + '个项目；'
            }
            if (props.rooms.stages.length) {
                rooms += props.rooms.stages.length + '个分期；'
            }
            if (props.rooms.building.length) {
                rooms += props.rooms.building.length + '栋楼；'
            }
            if (props.rooms.unit.length) {
                rooms += props.rooms.unit.length + '个单元；'
            }
            if (props.rooms.room.length) {
                rooms += props.rooms.room.length + '间房屋；'
            }
            if (rooms) {
                return '已选择' + rooms
            } else {
                return rooms
            }
        }
    } else {
        return data.roomLoader?.data?.address
    }
})

updateRoomLoader(props.room)

watch(() => props.room, async (value, oldValue) => {
    if (value !== oldValue) {
        updateRoomLoader(value)
    }
})
function updateRoomLoader(room?: string) {
    if (room) {
        data.roomLoader.load({ roomId: room })
    } else {
        data.roomLoader.clear()
    }
}

const inputRef = ref<ElInput>()

function updateRooms(rooms?: RoomSelector) {
    emit('update:rooms', rooms)
    inputRef.value!.focus()
    inputRef.value!.blur()
}
function onSingleInput(room: string) {
    emit('update:room', room)
    updateRooms({
        village: [],
        stages: [],
        building: [],
        unit: [],
        room: [String(room)]
    })
    data.isPopoverVisible = false
    resetDefaultChecked()
}

function onInput(rooms?: RoomSelector) {
    updateRooms(rooms)
    resetDefaultChecked()
}

const searchLoader = reactive(new Loader<api.Room[]>('/resource/info/selectAllRoomDataByWy'))
const search = debounce((keywords: string) => {
    searchLoader.clear()
    if (keywords) {
        searchLoader.load()
    }
}, 100)

function resetSearcher() {
    searchLoader.clear()
    searchLoader.baseParams = {}
}

function onSelect(room: api.Room) {
    if (props.multiple) {
        updateRooms({
            village: [],
            stages: [],
            building: [],
            unit: [],
            room: [String(room.id)]
        })
    } else {
        onSingleInput(String(room.id))
    }
    setDefaultChecked(room)
    data.isPopoverVisible = false
}

//点击搜索结果中的房间，在下次打开时要回显到树结构上
const treeSelectRef = ref<InstanceType<typeof MultipleSelect>|InstanceType<typeof SingleSelect>>()
const defaultRoom = ref<api.Room>()
const defaults = {
    expandedKeys: computed(() => {
        const room = defaultRoom.value
        if (room) {
            return [
                `village:${room.villageId}`,
                `stages:${room.stagesId}`,
                `building:${room.buildingId}`,
                `unit:${room.unitId}`
            ]
        }
    }),
    checkedKeys: computed(() => {
        const room = defaultRoom.value
        if (room) {
            return [`room:${room.id}`]
        }

    })
}
function setDefaultChecked(room: api.Room) {
    defaultRoom.value = room
    treeSelectRef.value?.setExpandedKeys(defaults.expandedKeys.value ?? [])
}
function resetDefaultChecked() {
    defaultRoom.value = undefined
}

</script>

<style scoped>

</style>